$(function () {
	//点击返回按钮返回上一页
	$(".goBack").bind("click",function(){
//		window.history.back();location.reload();	//强行刷新
//		window.history.go(-1);  //返回上一页
		window.location.href = document.referrer;	//返回上一页并刷新
	});
	
	//点击全部订单跳转到全部订单界面
	$(".order_ul .all").bind("click",function () {
		window.location.href = "allOrder.html"
	});
	//点击待付款跳转到待付款界面
	$(".order_ul .wait_pay").bind("click",function () {
		window.location.href = "waitPayOrder.html"
	});
	//点击待发货跳转到待发货界面
	$(".order_ul .wait_deliver").bind("click",function () {
		window.location.href = "waitDeliverOrder.html"
	});
	//点击退换货跳转到退换货界面
	$(".order_ul .wait_return").bind("click",function () {
		window.location.href = "tuihuanhuoOrder.html"
	});
	
	//点击订单获取订单号
	$(".orderList_box").bind("click",function(){
		var orderNum = $(this).find(".orderNum").text();
		console.log(orderNum);
	});

	// 获取零元购商城和集分商城的订单总页数
    var zeroPage = 0; // 零元购商城的订单总页数
    var jfscPage = 0; // 集分商城的订单总页数
    var flag1 = true;
    var flag2 = true;
	var zeroCode = 1;
	var JfscCode = 1;
    function getZeroPage(a) {
        return zeroPage = a;
    }
    function getJFSCPage(b) {
        return jfscPage = b;
    }
    function compare(a,b){
        return a > b ? a : b;
    }
    function Flag1(a){
        return flag1 = a;
    }
    function Flag2(a){
        return flag2 = a;
    }
	function getZeroCode(a){
		return zeroCode = a;
	}
	function getJfscCode(b){
		return JfscCode = b;
	}
	// 加载零元购商城和集分商城的订单
    dropload();
    function dropload() {
        var page = 0; //页码数
        // dropload函数接口设置
        $('.goodOrder').dropload({
            scrollArea: window,
            // 上拉加载更多
            domDown: {
                domClass: 'dropload-down',
                // 滑动到底部显示内容
                domRefresh: '<div class="dropload-refresh">上拉加载更多</div>',
                // 内容加载过程中显示内容
                domLoad: '<div class="dropload-load"><span class="loading"></span>加载中...</div>',
                // 没有更多内容显示提示
                domNoData: '<div class="dropload-noData">我也是有深度的...</div>'
            },
            // 上拉加载更多 回调函数
            loadDownFn: function(me) {
                page++; // 每次请求，页码加1
                if(flag1){
                    var load1 = $.ajax({
                        type: 'post',
						url: 'http://a.91jfk.com/Product/Order/zero_index?p=' + page,
						data:{
							state:'4'
						},
                        dataType: 'json',
                        success: function(res) {
                            console.log(res);
                            getZeroCode(res.code);
                            getZeroPage(res.totalpage);
                            // data = JSON.parse(res);
                            if (res.nowpage < res.totalpage) {
                                Flag1(true);
                                if (res.code == '1') {
                                    var data = res.msg;
                                    if (data.length > 0) {
                                        for (var i = 0; i < data.length; i++) {
                                            if(data[i].order_state == '已签收'){
                                                zeroSigned(data[i].orderid,data[i].order_state,data[i].product,res.nowpage,data[i].product.length,data[i].total);
                                            } 
                                            $('img.lazy'+res.nowpage).lazyload({
                                                placeholder:"/Public/Product/img/loading2.gif",
                                                effect: "fadeIn",
                                                container: $(".allOrderList")
                                            });
                                        }
                                        if(data.length < 3){
                                            // 显示无数据
                                            me.noData();
                                            // 重置
                                            setTimeout(function() {
                                                me.resetload();
                                            }, 1500);
                                        }
                                    }
                                    secondBuy();        // 再次购买
                                    setTimeout(function() {
                                        // 重置
                                        me.resetload();
                                    }, 1500);
                                    lookORconfirm();    //查看物流和确认收货，未签收订单
                                } else {
                                    me.noData();
                                    // 重置
                                    setTimeout(function() {
                                        me.resetload();
                                    }, 1500);
                                }
                            }else{
                                load1.abort();
                                Flag1(false);
                                if (res.code == '1') {
                                    var data = res.msg;
                                    for (var i = 0; i < data.length; i++) {
                                        if(data[i].order_state == '已签收'){
                                            zeroSigned(data[i].orderid,data[i].order_state,data[i].product,res.nowpage,data[i].product.length,data[i].total);
                                        }
                                        $('img.lazy'+res.nowpage).lazyload({
                                            placeholder:"/Public/Product/img/loading2.gif",
                                            effect: "fadeIn",
                                            container: $(".allOrderList")
                                        });
                                    }
                                    if(data.length < 3){
                                        // 显示无数据
                                        me.noData();
                                        // 重置
                                        setTimeout(function() {
                                            me.resetload();
                                        }, 1500);
                                    }
                                    secondBuy();        // 再次购买
                                } else {
                                    me.noData();
                                    me.lock();
                                    // 重置
                                    setTimeout(function() {
                                        me.resetload();
                                    }, 1500);
                                }
                            }
                            // 重置
                            setTimeout(function() {
                                me.resetload();
                            }, 1500);
                        },
                        // 加载出错
                        error: function(err) {
                            console.log('Ajax error!');
                            // 即使加载出错，也得重置
                            setTimeout(function() {
                                me.resetload();
                            }, 1500);
                        }
                    });
                }else{
                    var max = compare(zeroPage,jfscPage);
                    if (page > max) {
                        // 再往下已经没有数据，锁定
                        // 显示无数据
                        me.noData();
                        me.lock();
                        // 重置
                        setTimeout(function() {
                            me.resetload();
                        }, 1500);
                    } else {
                        me.unlock();
                    }
                }
                if(flag2){
                    var load2 = $.ajax({
                        type: 'post',
                        url: 'http://a.91jfk.com/Product/Ordershop/AllOrderData?p=' + page,
						data:{
							state:'4'
						},
                        dataType: 'json',
                        success: function(res) {
                            console.log(res);
                            getJfscCode(res.code);
                            getJFSCPage(res.total);
                            // data = JSON.parse(res);
                            if (res.nowpage < res.total) {
                                Flag2(true);
                                if (res.code == '1') {
                                    var data = res.message;
                                    if (data.length > 0) {
                                        for (var i = 0; i < data.length; i++) {
                                            if(data[i].order_state == '已签收'){
                                                signed(data[i].orderid,data[i].order_state,data[i].detail,res.nowpage,data[i].count,data[i].order_pay_price,data[i].order_pay_integral);
                                            } 
                                            $('img.lazy'+res.nowpage).lazyload({
                                                placeholder:"/Public/Product/img/loading2.gif",
                                                effect: "fadeIn",
                                                container: $(".allOrderList")
                                            });
                                        }
                                        if(data.length < 3){
                                            // 显示无数据
                                            me.noData();
                                            // 重置
                                            setTimeout(function() {
                                                me.resetload();
                                            }, 1500);
                                        }
                                        secondBuy();        // 再次购买
                                        return_goods();     // 申请退换货
                                    }
                                    setTimeout(function() {
                                        // 重置
                                        me.resetload();
                                    }, 1500);
                                } else {
                                    me.noData();
                                    // 重置
                                    setTimeout(function() {
                                        me.resetload();
                                    }, 1500);
                                }
                            }else{
                                load2.abort();
                                Flag2(false);
                                if (res.code == '1') {
                                    var data = res.message;
                                    for (var i = 0; i < data.length; i++) {
                                        if(data[i].order_state == '已签收'){
                                            signed(data[i].orderid,data[i].order_state,data[i].detail,res.nowpage,data[i].count,data[i].order_pay_price,data[i].order_pay_integral);
                                        }
                                        $('img.lazy'+res.nowpage).lazyload({
                                            placeholder:"/Public/Product/img/loading2.gif",
                                            effect: "fadeIn",
                                            container: $(".allOrderList")
                                        });
                                    }
                                    if(data.length < 3){
                                        // 显示无数据
                                        me.noData();
                                        // 重置
                                        setTimeout(function() {
                                            me.resetload();
                                        }, 1500);
                                    }
                                    secondBuy();        // 再次购买
                                    return_goods();     // 申请退换货
                                } else {
                                    me.noData();
                                    me.lock();
                                    // 重置
                                    setTimeout(function() {
                                        me.resetload();
                                    }, 1500);
                                }
                            }
                            setTimeout(function() {
                                me.resetload();
                            }, 1500);
                        },
                        // 加载出错
                        error: function(err) {
                            console.log('Ajax error!');
                            console.log(err);
                            // 即使加载出错，也得重置
                            setTimeout(function() {
                                me.resetload();
                            }, 1500);
                        }
                    });
                }else{
                    var max = compare(zeroPage,jfscPage);
                    if (page > max) {
                        // 再往下已经没有数据  锁定
                        // 显示无数据
                        me.noData();
                        me.lock();
                        // 重置
                        setTimeout(function() {
                            me.resetload();
                        }, 1500);
                    } else {
                        me.unlock();
                    }
                }
            }
        });
	}
    setTimeout(function(){
		if (zeroCode == 0 && JfscCode == 0) {
			$('.no_order').show();
			$('.no_order .img2').bind('click',function(){
				window.location.href = 'http://a.91jfk.com/Product/Pointshop/point_shop_index.html'
			});
            setTimeout(function(){
                $('div.dropload-noData').fadeOut(1000);
            },200);
		} else{
			$('.kong').hide();
		}
	},1500);
	
	// 再次购买
    function secondBuy() {
        //点击再次购买按钮的事件，首先阻止事件冒泡   
        $('.orderList_bot').off('click','.secondBuy').on('click','.secondBuy', function(e) {
            var evt = e || window.event; //兼容IE
            evt.stopPropagation();
            var OdNum = $(this).parents(".orderList_box").children(".orderList_num").children(".orderNum").text();
            console.log(OdNum);
            var orderList_con = $(this).parents(".orderList_box").children(".orderList_con");
            var arr = [];
            if (OdNum.substring(0,1) == 'Z') {
                for(var i = 0;i < orderList_con.length;i++){
                    var obj = {};
                    obj.goodId = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.input1').val();
                    obj.goodSrc = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.img').attr('src');
                    obj.goodName = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.goodTitle').text();
                    obj.goodPrice = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.price').text();
                    obj.goodNum = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.count').text();
                    obj.totalPrice = $(this).prev().children('.allPrice').text();
                    obj.totalNum = $(this).prev().children('.good_piece').text();
                    arr.push(obj);
                    Number = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.count').text();
                    Id = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.input1').val();
                    $.ajax({  
                        url:'http://a.91jfk.com/Product/Zero/cart', 
                        type:'post',  
                        dataType:'json',
                        data:{  
                            id:Id,
                            num:Number.substring(1,Number.length)
                        },  
                        success:function(res) { 
                            console.log(res);
                        },  
                        error : function(err) {    
                            console.log(err);
                        }  
                    });//ajax结束
                }
                console.log(arr);
                localStorage.setItem('thisZero',JSON.stringify(arr));
                window.location.href = '/Product/Zero/confirmOrder_zero.html';
            } else if(OdNum.substring(0,1) == 'J'){
                var goodType = $(this).parents(".orderList_bot").children('.inputType').val();
                console.log(goodType);  // 1、纯现金  3、纯集分  2、集分加现金
                for(var i = 0;i < orderList_con.length;i++){
                    var obj = {};
                    obj.goodId = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.input1').val();
                    obj.skuId = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.input2').val();
                    obj.skuState = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.sucesORfail').text();
                    obj.goodSrc = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.img').attr('src');
                    obj.goodName = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.goodTitle').text();
                    obj.goodPrice = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.price').text();
                    obj.goodNum = $(this).parents(".orderList_box").children(".orderList_con").eq(i).find('.count').text();
                    obj.totalPrice = $(this).prev().children('.allPrice').text();
                    obj.totalNum = $(this).prev().children('.good_piece').text();
                    obj.goodType = $(this).parents(".orderList_bot").children('.inputType').val();
                    arr.push(obj);
                }
                console.log(arr);
                var a = JSON.stringify(arr);
                window.localStorage.setItem('thisPoint',a);
                switch(goodType){
                    case '1':
                        window.location.href = '/Product/Zero/confirmOrder_mall.html';
                        break;
                    case '2':
                        window.location.href = '/Product/Zero/confirmOrder_exchange.html';
                        break;
                    case '3':
                        window.location.href = '/Product/Zero/confirmOrder_exchange.html';
                        break;
                    default:break;
                }
            }
        });
    }
	
	/*参数
	 * orderNum		订单编号
	 * state		订单状态
	 * src			商品图片地址
	 * title		商品名称
	 * price		商品单价
	 * states		商品交易状态
	 * count		单件商品的数量
	 * num			单笔订单里的商品总数
	 * total		单笔订单的总价
	*/

	//已签收
    function zeroSigned(orderNum, state, arr, j, num, total) {
        var List = $('.allOrderList');
        var listBox = $('<div class="orderList_box"></div>');
        var list_top = $('<div class="orderList_num"><span>订单编号：</span><span class="orderNum">' + orderNum + '</span><span class="TrsnState">' + state + '</span></div>');
        listBox.append(list_top);
        for (var i = 0; i < arr.length; i++) {
            var list_con = $('<div class="orderList_con"><input type="hidden" class="input1" value="' + arr[i].pid + '"><div class="orderList_con_lt"><div class="lt_imgBox"><img class="IMG lazy'+ j +'" src="/Public/Product/img/loading2.gif" data-original="' + arr[i].thumbnail + '" alt="" class="img"/></div></div><div class="orderList_con_rt"><p class="p_top"><span class="goodTitle">' + arr[i].title + '</span><span class="red price">&yen;' + arr[i].price + '</span></p><p class="p_bot"><span class="red count">x' + arr[i].num + '</span></p></div></div>');
            listBox.append(list_con);
        }
        var list_bot = $('<div class="orderList_bot"><p class="num-money">共<span class="good_piece pur">' + num + '</span>件商品，合计：&yen;<span class="allPrice pur">' + total + '元</span>(含运费&yen;3.0)</p><button class="seeExpress secondBuy fr">再次购买</button></div>');
        listBox.append(list_bot);
        List.append(listBox);
    }
	
	//已签收
    function signed(orderNum, state, arr, j, num, total1,total2) {
        var List = $('.allOrderList');
        var listBox = $('<div class="orderList_box"></div>');
        var list_top = $('<div class="orderList_num"><span>订单编号：</span><span class="orderNum">' + orderNum + '</span><span class="TrsnState">' + state + '</span></div>');
        listBox.append(list_top);
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].cash_price == '0.00' && arr[i].point_price != '0') {   //纯集分商品
                var list_con = $('<div class="orderList_con"><input type="hidden" class="input1" value="' + arr[i].id + '"><input type="hidden" class="input2" value="' + arr[i].skuid + '"><div class="orderList_con_lt"><div class="lt_imgBox"><img class="IMG lazy'+ j +'" src="/Public/Product/img/loading2.gif" data-original="' + arr[i].show_pic + '" alt="" class="img"/><span class="branchid" type="hidden">' + arr[i].branchid + '</span></div></div><div class="orderList_con_rt"><p class="p_top"><span class="goodTitle">' + arr[i].pname + '</span><span class="red price">&yen;' + arr[i].point_price + '集分</span></p><p class="p_bot"><span class="sucesORfail">' + arr[i].shuxing_zhi.replace(/'/g,'') + '</span><span class="red count">xx<m>' + arr[i].purchase_num + '</m></span></p></div></div>');
                listBox.append(list_con);
            }else if(arr[i].cash_price != '0.00' && arr[i].point_price != '0'){    //集分加现金商品
                var list_con = $('<div class="orderList_con"><input type="hidden" class="input1" value="' + arr[i].id + '"><input type="hidden" class="input2" value="' + arr[i].skuid + '"><div class="orderList_con_lt"><div class="lt_imgBox"><img class="IMG lazy'+ j +'" src="/Public/Product/img/loading2.gif" data-original="' + arr[i].show_pic + '" alt="" class="img"/><span class="branchid" type="hidden">' + arr[i].branchid + '</span></div></div><div class="orderList_con_rt"><p class="p_top"><span class="goodTitle">' + arr[i].pname + '</span><span class="red price">&yen;<m>' + arr[i].cash_price + '</m>元+<n>' + arr[i].point_price + '<n>集分</span></p><p class="p_bot"><span class="sucesORfail">' + arr[i].shuxing_zhi.replace(/'/g,'') + '</span><span class="red count">x<m>' + arr[i].purchase_num + '</m></span></p></div></div>');
                listBox.append(list_con);
            } else if(arr[i].cash_price != '0.00' && arr[i].point_price == '0'){   //纯现金商品
                var list_con = $('<div class="orderList_con"><input type="hidden" class="input1" value="' + arr[i].id + '"><input type="hidden" class="input2" value="' + arr[i].skuid + '"><div class="orderList_con_lt"><div class="lt_imgBox"><img class="IMG lazy'+ j +'" src="/Public/Product/img/loading2.gif" data-original="' + arr[i].show_pic + '" alt="" class="img"/><span class="branchid" type="hidden">' + arr[i].branchid + '</span></div></div><div class="orderList_con_rt"><p class="p_top"><span class="goodTitle">' + arr[i].pname + '</span><span class="red price">&yen;<m>' + arr[i].cash_price + '</m>元</span></p><p class="p_bot"><span class="sucesORfail">' + arr[i].shuxing_zhi.replace(/'/g,'') + '</span><span class="red count">x<m>' + arr[i].purchase_num + '</m></span></p></div></div>');
                listBox.append(list_con);
            }
        }
        if (total1 != '0.00' && total2 == '0') {     //纯现金商品
            var list_bot = $('<div class="orderList_bot"><p class="num-money">共<span class="good_piece pur">' + num + '</span>件商品，合计：&yen;<span class="allPrice pur">' + total1 + '元</span>(含运费&yen;3.0)</p><button class="seeExpress returnGoods">申请退货</button><button class="seeExpress secondBuy fr">再次购买</button><input type="hidden" class="inputType" value="1"></div>');
            listBox.append(list_bot);
        }else if(total1 == '0.00' && total2 != '0'){     //纯集分商品
            var list_bot = $('<div class="orderList_bot"><p class="num-money">共<span class="good_piece pur">' + num + '</span>件商品，合计：&yen;<span class="allPrice pur">' + total2 + '集分</span>(含运费&yen;3.0)</p><button class="seeExpress returnGoods">申请退货</button><button class="seeExpress secondBuy fr">再次购买</button><input type="hidden" class="inputType" value="3"></div>');
            listBox.append(list_bot);
        } else if(total1 != '0.00' && total2 != '0'){    //集分加现金商品
            var list_bot = $('<div class="orderList_bot"><p class="num-money">共<span class="good_piece pur">' + num + '</span>件商品，合计：&yen;<span class="allPrice pur">' + total1 + '元+' + total2 +'集分</span>(含运费&yen;3.0)</p><button class="seeExpress returnGoods">申请退货</button><button class="seeExpress secondBuy fr">再次购买</button><input type="hidden" class="inputType" value="2"></div>');
            listBox.append(list_bot);
        }
        List.append(listBox);
    }
    
    // 申请退换货
	function return_goods() {
		//点击再次购买按钮的事件，首先阻止事件冒泡   
        $(".allOrderList").on("click", ".returnGoods", function (e) {
            var evt = e || window.event; //兼容IE
            evt.stopPropagation();
            var img = $(this).parents(".orderList_bot").siblings(".orderList_con").find("img").attr("data-original");
            var shuxingzhi = $(this).parents(".orderList_bot").siblings(".orderList_con").find(".sucesORfail").text();
            var title = $(this).parents(".orderList_bot").siblings(".orderList_con").find(".goodTitle").text();
            var num = $(this).parents(".orderList_bot").siblings(".orderList_con").find(".count").children("m").text() - 0;
            var price = $(this).parents(".orderList_bot").siblings(".orderList_con").find(".price").children("m").text() - 0;
            var point = $(this).parents(".orderList_bot").siblings(".orderList_con").find(".price").children("n").text();
            var orderid = $(this).parents(".orderList_bot").siblings(".orderList_con").siblings(".orderList_num").find(".orderNum").text();
            var branchid = $(this).parents(".orderList_bot").siblings(".orderList_con").find(".branchid").text();
            var storage = window.localStorage;
            var obj = {
                title,
                img,
                shuxingzhi,
                num,
                price,
                orderid,
                branchid,
                point
            }
            obj.num = num;
            obj.price = price;
            obj.title = title;
            obj.shuxingzhi = shuxingzhi;
            obj.img = img;
            obj.orderid = orderid;
            obj.branchid = branchid;
            obj.point = point;
            var info = JSON.stringify(obj);
            storage.setItem("goods_info", info);
            window.location.href = "refund.html";
        });
	}
});